//
//  KZBaseVC.m
//  lg_zhinengbeikao_english
//
//  Created by 朱凯 on 2018/12/10.
//  Copyright © 2018年 zhukai. All rights reserved.
//

#import "KZBaseVC.h"

#import <objc/runtime.h>

@interface KZBaseVC ()
@property (nonatomic, strong) NSArray * leftItemviews;      // 左侧控件
@property (nonatomic, strong) NSArray * rightItemviews;     // 右侧控件


@end

@implementation KZBaseVC

/** 视图已经加载 */
- (void)viewDidLoad {
    
    [super viewDidLoad];

    if (@available(ios 11.0,*)) {
        
    } else {
        self.automaticallyAdjustsScrollViewInsets = false;
    }
    
    [self setupAnimatorAndGesture];
    self.view.backgroundColor = [UIColor whiteColor];   // 设置默认背景颜色
    self.tintColor = [UIColor whiteColor];              // 设置默认字体颜色
}

/** 视图将要出现，在该方法中设置导航栏的变动属性，本基类中定义默认属性，子类中要改变导航栏属性则需要覆写该方法 */
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    // 设置导航栏的默认属性(默认为不透明、黑色状态栏)
    [self setNaviAttributeWithTranslucent:false stateBarLightContent:true];
}
/** 视图已经出现 */
- (void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
}
/** 视图将要消失 */
- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
}
/** 视图已经消失 */
- (void)viewDidDisappear:(BOOL)animated {
    
    [super viewDidDisappear:animated];
}

#pragma mark - 转场动画 和 手势 设置，这里可以设置多种动画，使用时作不同的调用即可
- (void)setupAnimatorAndGesture {
    
    __weak typeof(self) weakself = self;
    _backCongfig = ^ {
        [weakself dismissViewControllerAnimated:true completion:nil];
    };
    
    // 基本的转场push动画
    _normalPushAnimator = [[KZNormalPushAnimator alloc] init];
    _normalPushAnimator.toDuration = _normalPushAnimator.backDuration = 0.3;
    
    // 侧滑
    _sideslipAnimator = [[KZSideslipAnimator alloc] init];
    _sideslipAnimator.toDuration = 0.3;
    _sideslipAnimator.backDuration = 0.15;
    _sideslipAnimator.backConfig = _backCongfig;
    
    // 仿淘宝详情规格选择
    _bottomPopAnimator = [[KZBottomPopAnimator alloc] init];
    _bottomPopAnimator.backConfig = _backCongfig;
}

#define KImageNaviBg 0
#define KImageNaviBgName @"LS-content_nav"
#define KWholeColorNaviBgColor kBlueColor
- (void)setNaviAttributeWithTranslucent:(BOOL)translucent
                   stateBarLightContent:(BOOL)light {
    
    // 设置状态栏
    [UIApplication sharedApplication].statusBarStyle = light ? UIStatusBarStyleLightContent : UIStatusBarStyleDefault;
    // 设置导航栏透明度
    self.navigationController.navigationBar.translucent = translucent;
    // 去掉导航栏背景色，用背景图代替
    self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];
    // 去掉导航栏下部的横线
    self.navigationController.navigationBar.shadowImage = translucent ? [UIImage imageWithColor:[UIColor clearColor]] : [UIImage imageWithColor:[UIColor colorWithWhite:0.8 alpha:0.5]];
    // 导航栏背景图
    UIImage *bgImage = nil;
    if (translucent) {
        self.navigationController.navigationBar.userInteractionEnabled = false;
        bgImage = [UIImage imageWithColor:[UIColor clearColor]];
    } else {
        self.navigationController.navigationBar.userInteractionEnabled = true;
        if (KImageNaviBg) {
            bgImage = [UIImage imageNamed:KImageNaviBgName];
        } else {
            bgImage = [UIImage imageWithColor:KWholeColorNaviBgColor];
        }
    }
    // 设置背景
    [self.navigationController.navigationBar setBackgroundImage:bgImage forBarMetrics:UIBarMetricsDefault];
}



#pragma mark ********** items **********
#define kLeftItemTagBase  1000
#define kRightItemTagBase 2000
#define kItemMargin       10
- (void)addLeftBackBarButtonItem {
    
    [self addNaviItems:@[@"navi_back"] mode:KZNavigationItemModeImage position:KZNavigationItemPositionModeLeft];
}
- (void)addNaviItemWithCustomViews:(NSArray *)views
                          position:(KZNavigationItemPositionMode)position {
    // 左侧
    if (position == KZNavigationItemPositionModeLeft) {
        
        NSMutableArray *temp = [[NSMutableArray alloc] init];
        for (UIView *leftView in views) {
            UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftView];
            [temp addObject:leftItem];
            
        }
        self.leftItemviews = temp.copy;
        self.navigationItem.leftBarButtonItems = temp.copy;
        
    }
    // 右侧
    else {
        
        NSMutableArray *temp = [[NSMutableArray alloc] init];
        for (UIView *rightView in views) {            
            UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightView];
            [temp addObject:rightItem];
        }
        self.rightItemviews = temp.copy;
        self.navigationItem.rightBarButtonItems = temp.copy;
    }
}
// 添加指定类型的 左右控件，根据mode来做不同的实现
- (void)addNaviItems:(NSArray *)items
                mode:(KZNavigationItemMode)mode
            position:(KZNavigationItemPositionMode)position {
    
    NSArray *views = [self createBYItems:items mode:mode position:position];
    [self addNaviItemWithCustomViews:views position:position];
}
// 创建左右控件元素
- (NSArray *)createBYItems:(NSArray *)items
                      mode:(KZNavigationItemMode)mode
                  position:(KZNavigationItemPositionMode)position {
    
    NSMutableArray *views = [[NSMutableArray alloc] initWithCapacity:items.count];
    switch (mode) {
        case KZNavigationItemModeImage: {
            CGFloat width = 40;
            CGFloat height = 44;
            for (int i = 0; i < items.count; i ++) {
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                button.tag = i + position == KZNavigationItemPositionModeLeft ? kLeftItemTagBase : kRightItemTagBase;
                button.frame = CGRectMake(0, 0, width, height);
                [button setImage:[UIImage imageNamed:items[i]] forState:UIControlStateNormal];
                [button addTarget:self action:@selector(btnTap:) forControlEvents:UIControlEventTouchUpInside];
                [views addObject:button];
                UIEdgeInsets edge = position == KZNavigationItemPositionModeLeft ? UIEdgeInsetsMake(12, -5, 12, 25) : UIEdgeInsetsMake(12, 25, 12, -5);
                [button setImageEdgeInsets:edge];
            }
        }
            break;
        case KZNavigationItemModeText: {
            CGFloat height = 44;
            for (int i = 0; i < items.count; i ++) {
                NSString *text = items[i];
                CGFloat width = [text getSizeOfString:16].width + 20;
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                button.tag = i + position == KZNavigationItemPositionModeLeft ? kLeftItemTagBase : kRightItemTagBase;
                button.frame = CGRectMake(0, 0, width, height);
                [button setTitle:text forState:UIControlStateNormal];
                [button setTitleColor:self.tintColor forState:UIControlStateNormal];
                button.titleLabel.font = FONT(16);
                [button addTarget:self action:@selector(btnTap:) forControlEvents:UIControlEventTouchUpInside];
                [views addObject:button];
                UIEdgeInsets edge = position == KZNavigationItemPositionModeLeft ? UIEdgeInsetsMake(12, -5, 12, 25) : UIEdgeInsetsMake(12, 25, 12, -5);
                [button setTitleEdgeInsets:edge];

            }
        }
            break;
        case KZNavigationItemModeImageAndText: {
            
            CGFloat height = 44;
            CGFloat margin = 4;
            for (int i = 0; i < items.count; i ++) {
                NSString *text = items[i];
                CGFloat width = [text getSizeOfString:12].width;
                width = width > 20 ? width : 20;
                UIControl *mixView = [[UIControl alloc] init];
                mixView.tag = i + position == KZNavigationItemPositionModeLeft ? kLeftItemTagBase : kRightItemTagBase;
                mixView.frame = CGRectMake(0, 0, width, height);
                [mixView addTarget:self action:@selector(btnTap:) forControlEvents:UIControlEventTouchUpInside];
                // 图片
                UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 15, 15)];
                imgView.image = [UIImage imageNamed:text];
                // 文字
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, 15)];
                label.font = FONT(12);
                label.text = text;
                label.textAlignment = NSTextAlignmentCenter;
                label.textColor = self.tintColor;
                
                [mixView addSubview:imgView];
                [mixView addSubview:label];
                
                // 设置位置
                CGFloat remainY = mixView.height - imgView.height - label.height - margin;
                imgView.top = remainY / 2;
                imgView.centerX = mixView.width / 2;
                label.top = imgView.bottom + margin;
                
                [views addObject:mixView];
            }
        }
            break;
            
        default:
            break;
    }
    
    return views.copy;
}

#pragma mark - setter
// 改变左右控件的颜色
- (void)setTintColor:(UIColor *)tintColor {
    _tintColor = tintColor;
    if (self.leftItemviews) {
        for (UIBarButtonItem *item in self.leftItemviews) {
            [self checkColorForSubviews:item.customView];
        }
    }
    if (self.rightItemviews) {
        for (UIBarButtonItem *item in self.rightItemviews) {
            [self checkColorForSubviews:item.customView];
        }
    }
}
// 检查并设置左右控件的颜色
- (void)checkColorForSubviews:(UIView *)view {
    
    if ([view isKindOfClass:[UILabel class]]) {
        UILabel *label = (UILabel *)view;
        label.textColor = _tintColor;
    } else if ([view isKindOfClass:[UIButton class]]) {
        UIButton *button = (UIButton *)view;
        [button setTitleColor:_tintColor forState:UIControlStateNormal];
    } else {
        for (UIView *subview in view.subviews) {
            [self checkColorForSubviews:subview];
        }
    }
}

#pragma mark - 事件
- (void)onNaviItemClick:(KZNavigationItemPositionMode)position index:(NSInteger)index {
    
    if (position == KZNavigationItemPositionModeLeft && index == 0) {
        if (self.presentingViewController) {
            [self dismissViewControllerAnimated:true completion:nil];
        } else {
            [self pop];
        }
        
    }
}
#pragma mark - tap
- (void)btnTap:(UIButton *)button {

    if (button.tag >= kRightItemTagBase) {
        [self onNaviItemClick:KZNavigationItemPositionModeRight index:button.tag - kRightItemTagBase];
    } else {
        [self onNaviItemClick:KZNavigationItemPositionModeLeft index:button.tag - kLeftItemTagBase];
    }
}

#pragma mark - 跳转
- (void)push:(UIViewController *)vc {
    [self.navigationController pushViewController:vc animated:true];
}
- (void)pop {
    [self.navigationController popViewControllerAnimated:true];
}
- (void)popTo:(Class)vcCls isNearest:(BOOL)isNearest {
    UIViewController *targetVc = nil;
    for (UIViewController *vc in [self.navigationController.viewControllers reverseObjectEnumerator]) {
        if (strcmp(class_getName(vc.class), class_getName(vcCls)) == 0) {
            targetVc = vc;
            if (isNearest) {
                break;
            } else {
                continue;
            }
        }
    }
    if (targetVc) {
        [self.navigationController popToViewController:targetVc animated:true];
    }
}
- (void)popToRoot {
    [self.navigationController popToRootViewControllerAnimated:true];
}

- (void)present:(UIViewController *)vc {
    
    KZBaseNaviVC *pushVC = [[KZBaseNaviVC alloc] initWithRootViewController:vc];
    [self kz_presentViewController:pushVC animator:self.normalPushAnimator backInteractive:false];
}
- (void)present:(UIViewController *)vc withBackInteractive:(BOOL)withBackInteractive {
    
    KZBaseNaviVC *pushVC = [[KZBaseNaviVC alloc] initWithRootViewController:vc];
    [self kz_presentViewController:pushVC animator:self.normalPushAnimator backInteractive:withBackInteractive];
}

- (void)dismiss {
    [self dismissViewControllerAnimated:true completion:nil];
}
- (void)registerBackInteractive {
    
    [self kz_registerBackInteractive:nil gestureConfig:nil];
}



//- (void)pop:(NSString *)preVcName {
//
//    UIView *temp = [self.view snapshotViewAfterScreenUpdates:NO];
//
//    UINavigationController *rootVC = (UINavigationController *)self.presentingViewController;
//
//    while (rootVC.presentingViewController) {
//
//        UIViewController *vc = nil;
//
//        if ([rootVC isKindOfClass:[UINavigationController class]]) {
//            vc = ((UINavigationController *)rootVC).viewControllers[0];
//        }
//
//        rootVC = (UINavigationController *)rootVC.presentingViewController;
//
//        if ([vc isKindOfClass:NSClassFromString(preVcName)]) {
//
//            vc.title = self.title;
//            [vc.view addSubview:temp];
//
//            break;
//        }
//    }
//
//    [rootVC dismissViewControllerAnimated:YES completion:nil];
//}



@end
